import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/pick/ai/ai_logic.dart';
import 'package:ball_lion/entity/ai/model_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/utils/update_utils.dart';
import 'package:ball_lion/widgets/base/wqs_carousel_view.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/base/wqs_image.dart';
import 'package:ball_lion/widgets/loading/shimmer_loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/base/base_builder.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class AiPage extends StatefulWidget {
  const AiPage({super.key, this.showAppBar = false});

  final bool showAppBar;

  @override
  State<AiPage> createState() => _AiPageState();
}

class _AiPageState extends State<AiPage> {
  final AiLogic logic = Get.put(AiLogic());

  @override
  Widget build(BuildContext context) {
    return RefreshBuilder<AiLogic>(
      header: Styles.refreshHeader(position: IndicatorPosition.locator),
      scrollController: logic.scrollController,
      builder: (AiLogic logic, BuildContext context, ScrollPhysics physics) {
        return VisibilityDetector(
          key: const Key("ai"),
          onVisibilityChanged: (VisibilityInfo info) {
            if (!info.visibleBounds.isEmpty) {
              Utils.onEvent("sj_mx");
              logic.getData();
            }
          },
          child: Scaffold(
            backgroundColor: Colours.transparent,
            appBar: widget.showAppBar
                ? Styles.appBar(
                    title: const QsText("模型"), automaticallyImplyLeading: true)
                : null,
            body: LoadingWidget<bool>(
              isLoading: logic.data == null,
              loading: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      clipBehavior: Clip.antiAlias,
                      margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                      decoration:
                          BoxDecoration(borderRadius: BorderRadius.circular(8)),
                      child: const ShimmerLoading(width: 359, height: 120),
                    ),
                    Container(height: 8),
                    Column(
                        children: List.generate(10, (index) => shimmerItem())),
                  ],
                ),
              ),
              data: false,
              child: () => CustomScrollView(
                  physics: physics,
                  controller: logic.scrollController,
                  slivers: [
                    const HeaderLocator.sliver(),
                    if (!widget.showAppBar)
                      SliverToBoxAdapter(child: Container(height: 8)),
                    if (logic.lbt.hasValue)
                      SliverToBoxAdapter(
                        child: QsCarouselView(
                          aspectRatio: 359 / 120,
                          radius: 8,
                          padding: 8,
                          needDot: (logic.lbt ?? []).length > 1,
                          carousels: logic.lbt ?? [],
                          tapType: "sycj_lbt",
                          needTitle: false,
                        ),
                      ),
                    SliverToBoxAdapter(child: Container(height: 8)),
                    LoadingWidget<bool>.sliver(
                      isLoading: logic.data?.length == null,
                      loading: const SliverToBoxAdapter(),
                      data: logic.data?.length == 0,
                      physics: physics,
                      reconnect: logic.getRefresh,
                      child: () => SliverList.list(
                          children: List.generate(logic.data?.length ?? 0,
                              (index) => aiItem(logic.data?[index], index))),
                    ),
                    SliverToBoxAdapter(child: Container(height: 50))
                  ]),
            ),
          ),
        );
      },
    );
  }

  Widget aiItem(ModelEntity? entity, int index) {
    return Stack(
      children: [
        Block(
            onTap: () async {
              Utils.onEvent('model_view', params: {'model_name': entity?.name});
              if (entity?.upgrade == true || entity?.page == null) {
                var tag = await Get.dialog(QsDialog.alert(
                    "工具模型算法已优化升级，请升级最新版本使用！",
                    cancelText: "关闭",
                    confirmText: "升级使用"));
                if (tag == true) UpdateUtils.checkUpdate();
              } else {
                Get.toNamed(entity?.page?.trim() ?? "");
              }
            },
            cardStyle: const CardStyle(
                margin: EdgeInsets.fromLTRB(8, 0, 8, 8),
                padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16)),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsImage(
                      imageUrl: entity?.logo,
                      width: 44,
                      height: 44,
                      fit: BoxFit.cover,
                      placeholder: Container(),
                      errorWidget: Styles.placeholderIcon(),
                    ),
                    Container(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              QsText(entity?.name ?? "", fontSize: 16),
                              if (entity?.openView?.endTime.hasValue == true)
                                QsText(
                                    "(${DateTime.parse(entity!.openView!.endTime!).formatedString("yyyy.MM.dd到期")})",
                                    needCenter: true,
                                    fontSize: 10,
                                    color: Colours.grey99)
                            ],
                          ),
                          Container(height: 2),
                          QsText(entity?.info ?? "", color: Colours.grey99),
                        ],
                      ),
                    )
                  ],
                ),
                Row(
                  children: [
                    Container(width: 44 + 16),
                    if (entity?.price == "限时免费")
                      Image.asset(
                          height: 18, Utils.getImgPath("free_for_now.png")),
                    if (entity?.price != null && entity?.price != "限时免费")
                      QsText((entity?.price ?? "-").changeUnit,
                          fontSize: 15,
                          color: Colours.main,
                          fontWeight: FontWeight.w500),
                    Container(width: 4),
                    if (entity?.priceOld != null)
                      QsText((entity?.priceOld ?? "-").changeUnit,
                          needCenter: true,
                          fontSize: 10,
                          decoration: TextDecoration.lineThrough,
                          color: Colours.grey99),
                    const Spacer(),
                    QsText(entity?.sales ?? "",
                        fontSize: 12, color: Colours.grey99),
                  ],
                )
              ],
            )),
        if (entity?.tag != null && ModeConfig.aiRecord) ...[
          Positioned(
            top: 0,
            right: 8,
            child: Container(
              height: 20,
              constraints: const BoxConstraints(minWidth: 79),
              padding: const EdgeInsets.only(left: 12, right: 8),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage(Utils.getImgPath("ai_tag.png")))),
              child: QsText(entity?.tag ?? "",
                  needCenter: true, fontSize: 12, color: Colours.white),
            ),
          )
        ]
      ],
    );
  }

  Widget shimmerItem() {
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 0, 8, 8),
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16)),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                QsImage(
                  imageUrl: null,
                  width: 44,
                  height: 44,
                  fit: BoxFit.cover,
                  placeholder: Container(),
                  errorWidget: Styles.placeholderIcon(),
                ),
                Container(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const ShimmerLoading(width: 16 * 8, height: 19),
                        ],
                      ),
                      Container(height: 2),
                      ShimmerLoading(width: Get.width, height: 19),
                    ],
                  ),
                )
              ],
            ),
            Row(
              children: [
                Container(width: 44 + 16),
                const ShimmerLoading(width: 15 * 6, height: 19),
                const Spacer(),
                const ShimmerLoading(width: 12 * 5, height: 19)
              ],
            )
          ],
        ));
  }
}
